<template>
  <view class="container">
    <!-- 无设备提示 -->
    <view v-if="noDeviceFound">
      <up-modal :show="noDeviceFound" title="无此设备，请检查设备编号或重新扫码。" @confirm="confirm"></up-modal>
    </view>

    <view class="body">
      <!-- 搜索条 -->
      <up-sticky bgColor="#fff">
        <view class="search">
          <up-search placeholder="输入设备编号" v-model="sbbhSearchWord" @search="sbbhSearch" @custom="sbbhSearch"
            @clickIcon="scanQRCode" searchIcon="scan" scrollable="false" :show-action="false" />
        </view>
      </up-sticky>

      <!-- 设备列表（分页加载） -->
      <view class="task-list">
        <view class="task-item" @tap="dataInfo(item)" v-for="(item) in ListData" :key="item.plandateid">
          <view class="task-info">
            <view class="device-name">{{ item.sbmc }}</view>
            <view class="device-code">设备编号：{{ item.sbbh }}</view>
            <view class="location">使用部门：{{ item.bmmc }}</view>
          </view>
        </view>
      </view>

      <!-- 加载更多提示 -->
      <view class="load-more" v-if="ListData.length < total">
        <u-loadmore status="loading" />
      </view>
      <view class="load-more" v-else-if="ListData.length > 0">
        <u-loadmore status="nomore" />
      </view>
    </view>

    <!-- 设备信息弹窗 -->
    <popUp :show="showDetailPopup" :lineList="popupLineList" :data="popUpData" :defaultActive="popUpDeviceStatus"
      @close="showDetailPopup = false" @deviceStatusChange="onDeviceStatusChange" @viewMore="handleViewMore" />

  </view>
</template>

<script>
import popUp from '@/components/popUp/popCenter.vue';

export default {
  components: {
    popUp
  },
  data() {
    return {
      sbbhSearchWord: '',
      ListData: [],
      pageIndex: 1,
      pageSize: 10,
      total: 0,
      showDetailPopup: false,
      noDeviceFound: false,
      popUpData: {},
      popupLineList: [
        { name: '设备名称', label: 'sbmc' },
        { name: '设备编号', label: 'sbbh' },
        { name: '使用部门', label: 'bmmc' },
        { name: '开机时间', label: 'beginTime' },
        { name: '关机时间', label: 'endTime' }
      ],
      popUpDeviceStatus: false, // false = “关闭”，true = “开启”
      sbtsData: {},
    };
  },
  onLoad() {
    this.getDeviceData();
  },

  // 滚动加载下一页
  onReachBottom() {
    if (this.ListData.length >= this.total) return;
    this.pageNum++;
    this.getDeviceData();
  },
  methods: {
    // 搜索设备并弹窗
    async sbbhSearch() {
      this.noDeviceFound = false;
      const keyword = this.sbbhSearchWord.trim();

      if (!keyword) {
        this.pageNum = 1;
        this.ListData = [];
        await this.getDeviceData();
        return;
      }

      // 直接调用API搜索
      this.pageNum = 1;
      await this.getDeviceData();

      // 检查是否有数据
      if (this.ListData.length === 0) {
        this.noDeviceFound = true;
      } else {
        const res = await this.$commonUnits.postRequest(
          "sbby.sbtzyxts.sbtsSelect.mobile",
          { "sbbh": this.ListData[0].sbbh }
        );

        this.popUpData = {
          bmmc: this.ListData[0].bmmc,
          sbbh: this.ListData[0].sbbh,
          sbmc: this.ListData[0].sbmc,
          beginTime: res.res.beginTime,
          endTime: res.res.endTime
        };
        
        if (res.res.endTime === null) {
          this.popUpDeviceStatus = true; // 控制打开时的状态
        } else {
          this.popUpDeviceStatus = false; // 控制打开时的状态
        }

        this.showDetailPopup = true;

      }
    },

    // 模拟数据源
    // 修改后的 getAllMockData 方法（建议重命名为 getDeviceData）
    async getDeviceData() {
      const currentParams = {
        sbbh: this.sbbhSearchWord
      };

      // 如果搜索条件变化，重置分页
      if (JSON.stringify(currentParams) !== JSON.stringify(this.searchParams)) {
        this.pageNum = 1;
        this.ListData = [];
      }

      this.searchParams = { ...currentParams };

      const params = {
        ...currentParams,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };

      try {
        const res = await this.$commonUnits.postRequest(
          "sbby.zcglsbtzbiz.getZcglSbtzBySbbh.mobile",
          params
        );
        if (!res.res.list || res.res.list.length === 0) {
          this.ListData = [];
          // uni.showToast({
          //   title: '暂无数据',
          //   icon: 'none'
          // });
        } else {
          // 确保字段映射正确
          const newData = res.res.list.map(item => ({
            plandateid: item.id || item.id, // 使用实际返回的ID字段
            sbmc: item.sbmc || item.sbmc, // 根据实际返回字段调整
            sbbh: item.sbbh || item.sbbh,  // 根据实际返回字段调整
            bmmc: item.bmmc || item.bmmc   // 根据实际返回字段调整
          }));

          this.total = res.res.total;

          if (this.pageNum === 1) {
            this.ListData = newData;
          } else {
            console.log('拼接上下一页数据');

            this.ListData = [...this.ListData, ...newData];
          }
        }
      } catch (err) {
        this.ListData = [];
        uni.showToast({
          title: '数据加载失败',
          icon: 'none'
        });
      }
    },

    // 分页加载数据
    async loadPageData() {
      const all = this.getDeviceData();
      this.total = all.length;
      const start = (this.pageIndex - 1) * this.pageSize;
      const end = start + this.pageSize;
      const pageData = all.slice(start, end);
      this.ListData = [...this.ListData, ...pageData];
    },



    // 弹窗选中事件
    handleViewMore(deviceData) {
      const encodedDeviceData = encodeURIComponent(JSON.stringify(deviceData));
      console.log('跳转查看设备详情：', encodedDeviceData);
      uni.navigateTo({
        url: `/pagesOne/pages/hours/detail?deviceId=${encodedDeviceData}`
      });
    },

    onDeviceStatusChange(payload) {
      console.log('设备状态改变：', payload.status);
      console.log('当前记录：', payload.record);
      // 获取数据
      if (payload.record.end == undefined) {
        this.sbtsData = {
          status: payload.status,
          beginTime: payload.record.start,
          endTime: "",
          department: payload.record.device.bmmc,
          deviceName: payload.record.device.sbmc,
          deviceCode: payload.record.device.sbbh
        };
      } else {
        this.sbtsData = {
          status: payload.status,
          beginTime: payload.record.start,
          endTime: payload.record.end,
          department: payload.record.device.bmmc,
          deviceName: payload.record.device.sbmc,
          deviceCode: payload.record.device.sbbh
        };
      }

      console.log(this.sbtsData);

      // 发送请求更新状态
      const json = JSON.stringify(this.sbtsData);

      this.$commonUnits.postRequest(
        "sbby.sbtzyxts.addSbsj.mobile",
        { "sbtsData": json }
      ).then(async () => {
        // 状态更新成功后，重新获取最新数据
        const res = await this.$commonUnits.postRequest(
          "sbby.sbtzyxts.sbtsSelect.mobile",
          { "sbbh": this.popUpData.sbbh } // 使用当前弹窗中的设备编号
        );

        // 更新弹窗数据
        this.popUpData = {
          sbmc: res.res.deviceName,
          sbbh: res.res.deviceCode,
          bmmc: res.res.department,
          beginTime: res.res.beginTime,
          endTime: res.res.endTime
        };

        // 保持弹窗打开
        this.showDetailPopup = true;

        uni.showToast({
          title: '状态更新成功',
          icon: 'success'
        });
      }).catch(err => {
        uni.showToast({
          title: '状态更新失败',
          icon: 'none'
        });
        console.error(err);
      });
    },

    // 扫码功能
    scanQRCode() {
      uni.scanCode({
        success: (res) => {
          this.sbbhSearchWord = res.result;
          this.sbbhSearch();
        },
        fail: () => {
          uni.showToast({ title: '扫码失败', icon: 'none' });
        }
      });
    },

    // 点击设备列表项跳转
    async dataInfo(item) {
      //获取数据
      const res = await this.$commonUnits.postRequest(
        "sbby.sbtzyxts.sbtsSelect.mobile",
        { "sbbh": item.sbbh }
      );

      var department = res.res.department;
      var deviceCode = res.res.deviceCode;
      var deviceName = res.res.deviceName;
      var beginTime = res.res.beginTime;
      var endTime = res.res.endTime;


      console.log(item)
      // const { plandateid, ...popUpData } = item;
      // this.popUpData = popUpData;
      this.popUpData = {
        sbmc: item.sbmc,
        sbbh: item.sbbh,
        bmmc: item.bmmc,
        beginTime: beginTime,
        endTime: endTime
      }

      if (endTime === null) {
        this.popUpDeviceStatus = true; // 控制打开时的状态
      } else {
        this.popUpDeviceStatus = false; // 控制打开时的状态

      }

      console.log(this.popUpData)
      // this.popUpDeviceStatus = false; // 控制打开时的状态
      this.showDetailPopup = true;
    },
    confirm() {
      this.noDeviceFound = false;
    },
  }
};
</script>

<style src="./hours.css"></style>
<style scoped>
.u-popup {
  z-index: 9999 !important;
}
</style>
